package com.wang.springbootinit.aop;

import com.wang.springbootinit.annotation.TestRunTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class RunTimeInterceptor {

    @Around("@annotation(testRunTime)")
    public Object doInterceptor(ProceedingJoinPoint point, TestRunTime testRunTime) throws Throwable {
        //获取进入到当前controller的request
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //根据切面获取方法信息
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        log.info("getTarget " + point.getTarget().toString());
        Method method = methodSignature.getMethod();
        String methodName = method.getName();
        StringBuilder builder = new StringBuilder();
        builder.append("测试的方式名：" + methodName + " 参数: ");
        Object[] args = point.getArgs();
        for (Object arg : args) {
            builder.append(arg + " ");
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object proceed = point.proceed();
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        builder.append(" 方法执行时间：" + totalTimeMillis);
        log.info(builder.toString());
        return proceed;
    }
}
